#include <iostream>
#include <string>
#include <vector>
using namespace std;

#include <boost/algorithm/string.hpp>
using namespace boost;

#include <boost/lexical_cast.hpp>

#include <boost/smart_ptr.hpp>
#include <boost/make_shared.hpp>

using namespace boost::algorithm;
#include <boost/typeof/typeof.hpp>
#include <boost/assign.hpp>
#include <boost/pool/pool.hpp>

#define BOOST_SYSTEM_NO_DEPRECATED

#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>
using namespace boost::system;
using namespace boost::system::errc;

#include <boost/asio.hpp>
#include <boost/thread.hpp>
using namespace boost::asio;
/*

namespace boost
{
    namespace system
    {
    class My_Err : public error_category
{
public:
     const char *     name() const {return "fk";}
     std::string      message( int ev ) const {return "shit";}
};

My_Err g_err;

           BOOST_SYSTEM_DECL const error_category &  get_system_category(){return g_err;}
        BOOST_SYSTEM_DECL const error_category &  get_generic_category(){return g_err;}

    }

}
*/

void Stream_Server()
{
    io_service ios;
	ip::tcp::acceptor apt(ios,ip::tcp::endpoint(ip::tcp::v4(),8888));
	while (true)
	{
		ip::tcp::iostream tcp_server;
		apt.accept(*tcp_server.rdbuf());
		string str;
		do
		{
			getline(tcp_server,str);
			cout<<str<<endl;
			trim(str);
		} while (!str .empty());

		tcp_server<<"HTTP/1.1 200 OK\r\n\r\n<html><h>what the fk</h></html>";
	}


}


#include "BoostAsyncSocket.h"

void Test(CBoostAsyncServerSocket* pBASS)
{
	//io_service ios;
	//deadline_timer dt(ios,posix_time::seconds(20));

	////cout<<dt.expires_at()<<endl;

	//dt.wait();
	for (int i = 0; i < 2;i++)
	{
		cout<<"Waiting ..."<<endl;
		pBASS->WaitForFinish();
		cout<<"Finish one"<<endl;

	}
	pBASS->Stop();
}

void SockFinish(sock_pt sock)
{
	cout<<"sock finish:"<<sock->remote_endpoint().address()<<":"<<sock->remote_endpoint().port()<<endl;
}

void SockFinish2(sock_pt sock)
{
	cout<<"sock finish 2:"<<sock->remote_endpoint().address()<<":"<<sock->remote_endpoint().port()<<endl;
}



void Exit()
{
	//int i = _CrtDumpMemoryLeaks();
	//assert( i == 0);
//	int j =i;
}

void Test_Server()
{
	CBoostAsyncServerSocket bas;
	bas.Init(8888);
	bas.Start();
	bas.RegisterFinishNotify(&SockFinish);
	bas.RegisterFinishNotify(&SockFinish2);
	thread_group tg;
	//thread t1(&CBoostAsyncServerSocket::Run,&bas);
	//thread t2(&Test,&bas);

	//t1.join();

	tg.create_thread(bind(&CBoostAsyncServerSocket::Run,&bas));
	tg.create_thread(bind(&Test,&bas));

	tg.join_all();

	io_service ios;
	deadline_timer dt(ios,posix_time::seconds(2));

	dt.wait();
}

void Test_Client()
{
	CBoostAsyncClientSocket bacs;
	//bacs.Connect("61.135.169.105",80);
    bacs.Connect("www.baidu.com");
	thread t1(&CBoostAsyncClientSocket::Run,&bacs);

	t1.join();
}




int main()
{
    try
	{
		//Test_Server();
        Test_Client();
	}
	catch(std::exception& e)
	{
		cout<<e.what()<<endl;
	}

    return 0;
}
